package org.marsdonne.commons.wechat;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.marsdonne.archives.Client;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

@Component
@EnableConfigurationProperties(AppSecretProps.class)
public class AccessTokenServImpl implements AccessTokenServ {

    @Resource
    private AppSecretProps appSecrets;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public Map getToken(Client client) {
        AppSecret appSecret = this.appSecrets.getAppSecrets().get(client.name());

        ResponseEntity<String> responseEntity = restTemplate.getForEntity(API_GET_ACCESS_TOKEN_URL, String.class, appSecret.getAppId(), appSecret.getSecret());

        return convert(responseEntity);
    }

    private Map convert(ResponseEntity<String> responseEntity) {
        Map resp = null;

        try {
            resp = this.objectMapper.readValue(responseEntity.getBody(), Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return resp;
    }
}
